package com.zjy.weather.util;

import android.app.ActivityManager;
import android.app.DownloadManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Created by wiikii on 16/10/31.
 * Copyright (C) 2014 wiikii. All rights reserved.
 */
public class SystemUtils {
    /**
     * Judge the network is available.
     * @return boolean
     */
    public static boolean isNetworkAvailable(Context context) {
        try {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            if (manager == null) {
                return false;
            }

            NetworkInfo networkinfo = manager.getActiveNetworkInfo();
            return !(networkinfo == null || !networkinfo.isAvailable());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * get the current available network's type
     * @return -1 if the network is unavailable, or return other types defined by ConnectivityManager.
     */
    public static int getCurNetworkType(Context context) {
        try {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (manager == null) {
                return -1;
            }

            NetworkInfo networkInfo = manager.getActiveNetworkInfo();
            if (networkInfo == null || !networkInfo.isAvailable()) {
                return -1;
            }

            return networkInfo.getType();
        } catch (Exception e) {
            return -1;
        }
    }

    /**
     * Judge the current network is WIFI.
     * @return boolean
     */
    public static boolean isCurrentUseWifi(Context context) {
        int type = getCurNetworkType(context);
        return type == ConnectivityManager.TYPE_WIFI;

    }

    /**
     * Judge the current network is MOBILE.
     * @return boolean
     */
    public static boolean isCurrentUseMobile(Context context) {
        int type = getCurNetworkType(context);
        return type == ConnectivityManager.TYPE_MOBILE;

    }

    public static String getUmengChannelValue(Context context) {
        return getAppMetaData(context, "UMENG_CHANNEL");
    }

    public static String getAppMetaData(Context context, String key) {
        if (context == null || TextUtils.isEmpty(key)) {
            return "";
        }
        String resultData = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(
                        context.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null && applicationInfo.metaData != null) {
                    resultData = applicationInfo.metaData.getString(key);
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return resultData == null ? "" : resultData;
    }

    public static int getVersionCode(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
                    context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            return packageInfo.versionCode;
        } catch (Exception e) {
            return 0;
        }
    }

    public static String getVersionName(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
                    context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            return packageInfo.versionName;
        } catch (Exception e) {
            return "";
        }
    }

    public static void installApk(Context context, File file) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static boolean startSystemDownload(Context context, String downloadUrl, String mimeType) {
        if (context == null || TextUtils.isEmpty(downloadUrl)) {
            return false;
        }
        try {
            DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
            File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1);
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            if (downloadUrl.endsWith(".apk")) {
                request.setMimeType("application/vnd.android.package-archive");
            } else {
                if (mimeType != null) {
                    request.setMimeType(mimeType);
                }
            }

            if (!isProcessDownloadRequest(downloadManager, downloadUrl)) {
                downloadManager.enqueue(request);
            } else {
                Toast.makeText(context, "已加入下载队列", Toast.LENGTH_SHORT).show();
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean isProcessDownloadRequest(DownloadManager mgr, String downloadUrl) {
        if (mgr == null || TextUtils.isEmpty(downloadUrl)) {
            return false;
        }

        DownloadManager.Query query = new DownloadManager.Query();
        Cursor cursor = mgr.query(query);
        if (cursor == null) {
            return false;
        }

        while (cursor.moveToNext()) {
            String url = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI));
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
//            String filePath = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); // file:///storage/emulated/0/Download/2345Browser_8.8.2.apk
//            String fileName = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME)); // /storage/emulated/0/Download/2345Browser_8.8.2.apk
            if (downloadUrl.equals(url) && status != DownloadManager.STATUS_FAILED) {
                SystemUtils.closeCursor(cursor);
                return true;
            }
        }

        SystemUtils.closeCursor(cursor);
        return false;
    }

//    public static void saveDownloadIdList(Context context, String downloadId) {
//        List<String> downloadIdList = SPManager.getStringList(context, DOWNLOAD_ID_LIST_KEY);
//        if (downloadIdList == null) {
//            downloadIdList = new ArrayList<>();
//            downloadIdList.add(0, downloadId);
//        } else {
//            if (!downloadIdList.contains(downloadId)) {
//                downloadIdList.add(0, downloadId);
//            }
//        }
//
//        // 处理下载ID的长度限制
//        int maxSize = 25;
//        if (downloadIdList.size() > maxSize) {
//            downloadIdList = downloadIdList.subList(0, maxSize);
//        }
//        SPManager.setStringList(context, DOWNLOAD_ID_LIST_KEY, downloadIdList);
//    }
//
//    public static boolean containDownloadId(Context context, String downloadId) {
//        // 处理此下载是否我们自己的下载
//        List<String> downloadIdList = SPManager.getStringList(context, SystemUtils.DOWNLOAD_ID_LIST_KEY);
//        if (downloadIdList == null) {
//            return false;
//        }
//
//        if (!downloadIdList.contains(downloadId)) {
//            return false;
//        }
//
//        downloadIdList.remove(String.valueOf(downloadId));
//        SPManager.setStringList(context, SystemUtils.DOWNLOAD_ID_LIST_KEY, downloadIdList);
//        return true;
//    }

    public static String getStringFromAssetFile(Context context, String fileName) {
        InputStream inputStream = null;
        try {
            inputStream = context.getAssets().open(fileName);
            return readStringFromStream(inputStream);
        } catch (Exception e) {
            return null;
        } finally {
            closeStream(inputStream);
        }
    }

    public static String getStringFromRawFile(Context context, int resourceId) {
        InputStream inputStream = null;
        try {
            inputStream = context.getResources().openRawResource(resourceId);
            return readStringFromStream(inputStream);
        } catch (Exception e) {
            return null;
        } finally {
            closeStream(inputStream);
        }
    }

    private static String readStringFromStream(InputStream is) {
        InputStreamReader reader = null;
        BufferedReader bufferedReader = null;
        try {
            reader = new InputStreamReader(is);
            bufferedReader = new BufferedReader(reader);
            StringBuffer buffer = new StringBuffer("");
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            return buffer.toString();
        } catch (Exception e) {
            return null;
        } finally {
            closeStream(bufferedReader);
            closeStream(reader);
        }
    }

    public static File getAppStorageDirectory() {
        File externStorageDir = Environment.getExternalStorageDirectory();
        File appStorageDir = new File(externStorageDir, "Calendar2345");
        if (!appStorageDir.exists()) {
            appStorageDir.mkdirs();
        }

        return appStorageDir;
    }

    public static File getUpdateStorageDirectory() {
        File dir = new File(getAppStorageDirectory(), "update");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        return dir;
    }

    public static File getDownloadDirectory() {
        File dir = new File(getAppStorageDirectory(), "download");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        return dir;
    }

    public static void clipboard(Context context, String text) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        clipboardManager.setText(text);
    }

    public static void closeStream(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void closeCursor(Cursor cursor) {
        try {
            if (cursor != null) {
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static File getDiskCacheDir(Context context, String uniqueName) {
        try {
            Context applicationContext = context.getApplicationContext();
            String cachePath;
            if ((Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                    || !Environment.isExternalStorageRemovable())
                    && applicationContext.getExternalCacheDir() != null) {
                cachePath = applicationContext.getExternalCacheDir().getPath();
            } else {
                File cacheDir = applicationContext.getCacheDir();
                if (cacheDir == null) {
                    return null;
                }
                cachePath = cacheDir.getPath();
            }

            File file = new File(cachePath + File.separator + uniqueName);
            if (!file.exists()) {
                file.mkdirs();
            }

            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void clearFile(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return;
        }

        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            file.delete();
        }
    }

    public static boolean appInstalled(Context context, String packageName) {
        PackageInfo packageInfo = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            packageInfo = packageManager.getPackageInfo(
                    packageName, PackageManager.GET_ACTIVITIES);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (packageInfo == null) {
            return false;
        }

        return true;
    }

    public static final String[] WEATHER_2345_PACKAGE_NAMES = {
        "com.tianqi2345", "com.tianqiwhite", "com.tianqiyubao2345"
    };



    public static String getSPAppVersion(Context context) {
        String versionName = getVersionName(context);
        int versionCode = getVersionCode(context);
        return versionName + String.valueOf(versionCode);
    }

    private static final String SP_APP_VERSION_KEY = "sp_app_version_key";



    /**
     * 判断服务是否在运行.
     */
    public static boolean isServiceRunning(Context context, String serviceName) {
        if (context == null || TextUtils.isEmpty(serviceName)) {
            return false;
        }
        try {
            ActivityManager manager = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            if (manager != null) {
                for (ActivityManager.RunningServiceInfo service
                        : manager.getRunningServices(Integer.MAX_VALUE)) {
                    if (serviceName.equals(service.service.getClassName())) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * Returns whether the SDK is the Jellybean release or later.
     */
    public static boolean isJellybeanOrLater() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
    }

    /**
     * Returns whether the SDK is the KeyLimePie release or later.
     */
    public static boolean isKeyLimePieOrLater() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    }

    /**
     * 弹出软键盘.
     */
    public static void showSoftKeyBoard(Context context, View view) {
        if (context == null || view == null) {
            return;
        }
        try {
            InputMethodManager inputMethodManager = ((InputMethodManager) context
                    .getSystemService(Context.INPUT_METHOD_SERVICE));
            inputMethodManager.showSoftInput(view, 0);
        } catch (Exception e) {
            Log.e("wiikzz", " showSoftKeyBoard has error:" + e.getMessage());
        }
    }

    /**
     * 隐藏软键盘.
     */
    public static void hideSoftKeyBoard(Context context, View view) {
        if (context == null || view == null) {
            return;
        }
        try {
            InputMethodManager inputMethodManager = ((InputMethodManager) context
                    .getSystemService(Context.INPUT_METHOD_SERVICE));
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        } catch (Exception e) {
            Log.e("wiikzz", "hideSoftKeyBoard has error:" + e
                    .getMessage());
        }
    }


    /**
     * 获取进程名称.
     */
    public static String getProcessName(Context cxt, int pid) {
        try {
            ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
            if (runningApps == null) {
                return null;
            }
            for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
                if (procInfo.pid == pid) {
                    return procInfo.processName;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断当前进程是否是主进程.
     */
    public static boolean isMainProcess(Context context) {
        if (context == null) {
            return false;
        }
        try {
            int pid = android.os.Process.myPid();
            String processName = SystemUtils.getProcessName(context, pid);
            String defaultProcessName = context.getPackageName();
            return defaultProcessName.equals(processName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 进入设置系统应用权限界面.
     */
    public static void startSetting(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            context.startActivity(intent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            context.startActivity(intent);
        }
    }

    /**
     * 启动服务.
     */
    public static void startService(Context context, Intent intent) {
        if (context == null || intent == null) {
            return;
        }
        try {
            context.startService(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动服务.
     */
    public static void startService(Context context, Class<?> cls) {
        if (context == null || cls == null) {
            return;
        }
        Intent intent = new Intent(context,cls);
        startService(context,intent);
    }

    /**
     * 启动服务.
     */
    public static void startService(Context context, ComponentName componentName) {
        if (context == null || componentName == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setComponent(componentName);
        startService(context, intent);
    }

    /**
     * 判断Activity是否正在运行.
     */
    public static boolean isActivityExists(Context context, Class<?> cls) {
        try {
            if (context == null) {
                return false;
            }
            Intent intent = new Intent(context, cls);
            ComponentName cmpName = intent.resolveActivity(context.getPackageManager());
            boolean flag = false;
            if (cmpName != null) {
                ActivityManager am = (ActivityManager) context.getSystemService(
                        Context.ACTIVITY_SERVICE);
                List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
                for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                    if (taskInfo.baseActivity.equals(cmpName)) { // 说明已经启动
                        flag = true;
                        break;
                    }
                }
            }
            return flag;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
